package com.codeerror.demo.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.codeerror.demo.R;
import com.codeerror.demo.bean.Star;

import java.util.List;

public class StarRecyclerAdapter extends RecyclerView.Adapter<StarRecyclerAdapter.ViewHolder>{

    //设置数据源
    private List<Star> stars;
    public void setStars(List<Star> stars) {
        this.stars = stars;
    }


    //监听点击事件外部接口
    private OnItemClickListener mOnItemClickListener;
    public interface OnItemClickListener {
        void onItemClick(View view, int position, Star star);
    }
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }


    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        if(viewType == 0){
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_star_recycler_left,parent,false);
        }else {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_star_recycler_right,parent,false);
        }
        ViewHolder viewHolder;
        viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Star star = stars.get(position);
        holder.starImg.setImageResource(star.unlockedImageId);
        if(star.isUnlocked){
            holder.lockedImg.setVisibility(View.INVISIBLE);
        }
        //响应点击事件
        holder.rootView.setOnClickListener(v -> mOnItemClickListener.onItemClick(v, position,star));
    }

    @Override
    public int getItemCount() {
        return stars.size();
    }


    @Override
    public int getItemViewType(int position) {
        if(position % 2 == 0){
            return 0;
        }else return 1;
    }


    static class ViewHolder extends RecyclerView.ViewHolder{
        View rootView;
        ImageView starImg;
        ImageView lockedImg;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            this.rootView = itemView.findViewById(R.id.fit_item_view);
            starImg = itemView.findViewById(R.id.unlocked_star_image);
            lockedImg = itemView.findViewById(R.id.locked_star_image);
        }
    }
}

